<?php

namespace App\Http\Middleware;

use App\Helpers\Jwt;
use App\Models\Customer\User;
use App\Services\LoginAccountService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AccountLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $action = app('request')->route()->getAction();
        $controller = class_basename($action['controller']);
        list($controller, $action) = explode('@', $controller);
        $noLoginActs = ['LoginController'];
        $token = $request->headers->get('Authorization');
        if (strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new Jwt();
            $jwtAccount = $jwt->verifyToken($token) ?? '';
            if (!Str::startsWith($jwtAccount, LoginAccountService::ACCOUNT_PREFIX)) {
                $account = '';
            } else {
                $account = str_replace(LoginAccountService::ACCOUNT_PREFIX, '', $jwtAccount);
            }
            register('account', $account);
            $customerUser = User::byPhone($account)->first();
            register('customer_user', $customerUser);
        } else {
            $account = '';
        }
        if (!$account && !in_array($controller, $noLoginActs)) {
            return response()->json(message("请登录", false, null, 401));
        }
        return $next($request);
    }
}
